from flask import Blueprint, request
from core.services.user import UserService
from core.app.auth import check_password, create_token, auth
from core.app.errors import APIError

bp = Blueprint("user", __name__, url_prefix='/user')
userService = UserService()


@bp.route('/login', methods=['POST'])
def login():
    print('login')
    user = userService.get_by_username(request.form.get('username'))
    print(user)
    verify = check_password(request.form.get('password'), user.password)
    if verify:
        token = create_token(user.id)
        return {"data": token}
    else:
        raise APIError(403, 'Login Failed!')


@bp.route('/users')
@auth.login_required
def users():
    return {'data': 'users'}


@bp.route('/task')
def task():
    from core.tasks import add
    result = add.delay(1, 2)
    print(result.wait())
    return {"data": 'ok'}
